package com.woniuxy.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.text.ParseException;
import java.util.Map;

public class JWTUtil {

    //密文 secretKey
    private static final String secretKey = "xa3sd7a8sc9xd5s575dgd6c4vv6cc1bx8dfw8dfs3ad5sd2";

    public static String createJWT(Map<String, Object> userMap) throws JOSEException {
        //1. 生成头部
        JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256)
                .type(JOSEObjectType.JWT).build();

        //2. 生成载荷(用于保存用户信息)
        Payload payload = new Payload(userMap);

        //3. 生成数字签名 加密(头部+载荷+密码)
        JWSObject jwsObject = new JWSObject(header, payload);
        MACSigner macSigner = new MACSigner(secretKey);
        jwsObject.sign(macSigner); // 数字签名加密
        return jwsObject.serialize(); //通过序列化得到jwt字符串并返回
    }

    //解密JWT
    public static Boolean decode(String jwtStr) throws ParseException, JOSEException {

        JWSObject jwsObject = JWSObject.parse(jwtStr); //反序列化从字符串得到对象
        MACVerifier macVerifier = new MACVerifier(secretKey);
        return jwsObject.verify(macVerifier); //解密
    }

    //获取JWT中的用户信息
    public static Map<String, Object> getJWTUserInfo(String jwt) throws ParseException {
        JWSObject jwsObject = JWSObject.parse(jwt); //反序列化得到对象 字符串->对象
        return jwsObject.getPayload().toJSONObject();
    }
}
